// websocket-store.ts
import { Websocket } from 'hyper-express';

type ClientID = string;
type WebSocketClient = Websocket;

export interface WebSocketMessage {
  type: 'message' | 'system'
  content: string
  timestamp: number
  clientId?: string
}

class WebSocketStore {
  // 单例实例引用
  private static instance: WebSocketStore;
  // 线程安全的连接存储 (Node.js 单线程特性保证原子性)
  private clients: Map<ClientID, WebSocketClient>;
  // 心跳间隔 (毫秒)
  private readonly HEARTBEAT_INTERVAL = 25_000;

  private constructor() {
    this.clients = new Map();
  }

  // 获取单例实例
  public static getInstance(): WebSocketStore {
    if (!WebSocketStore.instance) {
      WebSocketStore.instance = new WebSocketStore();
    }
    return WebSocketStore.instance;
  }

  // 添加客户端连接
  public addClient(clientId: ClientID, ws: WebSocketClient): void {
    // 清理已存在的相同 ID 连接 (防止重复连接)
    if (this.clients.has(clientId)) {
      this.removeClient(clientId);
    }

    this.clients.set(clientId, ws);
    this.setupHeartbeat(clientId, ws);
    this.setupCloseHandler(clientId, ws);
  }

  // 获取客户端连接
  public getClient(clientId: ClientID): WebSocketClient | undefined {
    return this.clients.get(clientId);
  }

  // 移除客户端连接
  public removeClient(clientId: ClientID): void {
    const ws = this.clients.get(clientId);
    if (ws) {
      ws.close(); // 主动关闭连接
      this.clients.delete(clientId);
    }
  }

  // 心跳检测机制
  private setupHeartbeat(clientId: ClientID, ws: WebSocketClient): void {
    const interval = setInterval(() => {
      if (ws.writable) {
        ws.ping(); // 发送 ping 帧
      }
    }, this.HEARTBEAT_INTERVAL);

    // 绑定清理定时器逻辑
    ws.on('close', () => clearInterval(interval));
  }

  // 连接关闭处理器
  private setupCloseHandler(clientId: ClientID, ws: WebSocketClient): void {
    ws.on('close', () => {
      this.clients.delete(clientId);
      console.log(`连接 ${clientId} 已安全关闭`);
    });
  }
}

// 导出单例实例
export const webSocketStore = WebSocketStore.getInstance();